import React, { Component } from 'react'
import { HeaderBar, FooterBar, CartList, Toast, TotalPrice } from '../../components'
import '../../mock'
import cartStyle from './cart.module.scss'
import axios from 'axios'
export default class Cart extends Component {
  state = {
    // 只读
    showToast: false,
    list: [],
    totalPrice: 0,
    allChecked: false,
  }

  // 减少商品函数
  handleReduceItem(id) {
    const { list } = this.state
    let goods = list.find((v) => v.id === id)
    if (goods.number <= 1) {
      if (window.confirm('确认删除吗?')) {
        // 删除 调用：splice
        let copyList = [...this.state.list]
        copyList.splice(
          copyList.findIndex((v) => v.id === id),
          1
        )
        this.setState({ list: copyList })
      }
      return
    }
    goods.number--
    // 手动更新 调用render方法渲染页面
    this.setState({}) // render方法
    console.log('goods:', goods)
  }

  // ++
  handleAddItem(id) {
    const { list } = this.state
    let goods = list.find((v) => v.id === id)
    goods.number++
    /**
     *     let arr = [1, 2, 3]
     * arr.splice()
     * 引用类型 arr {} fun
     * 栈             堆
     *
     * arr 指针 ---  [1,2,3]
     *  --新指针             {}
     * diff
     * 旧dom 新dom
     * ()
     *
     * ({})
     */
    this.setState({}) // {}
  }

  // 反选函数
  handleSelected = ({ id, checked }) => {
    console.log(id, checked)
    this.state.list.forEach((item) => {
      if (item.id === id) {
        item.isSelected = checked
      }
    })
    // 根据每一个选中的项，去判断，总的选中项
    const allChecked = this.state.list.every((item) => {
      return item.isSelected
    })
    // 重新渲染
    this.setState({ allChecked })
  }

  async fetchCartData() {
    const response = await axios.get('/api/list')
    this.setState({
      list: response.data.data,
    })
  }

  componentDidMount() {
    this.fetchCartData()
  }

  // 计算总价
  getTotalPrice = () => {
    // reduce 第一个参数是一个回调函数，此回调函数的第一个参数，等于reduce的第二个参数
    return this.state.list.reduce((num, item) => {
      if (item.isSelected) {
        return num + item.price.toFixed(2) * 1000 * item.number
      } else {
        return num
      }
    }, 0)
  }

  render() {
    const { list, allChecked } = this.state
    return (
      <div className={cartStyle['cart-container']}>
        <TotalPrice totalPrice={this.getTotalPrice() / 1000} />
        {/* {{ a: 1 }} */}
        {/* {[1, 2, 3, 4]} */}

        {/* 全选 */}
        <input
          type="checkbox"
          checked={allChecked}
          onChange={(e) => {
            // 异步更新
            this.setState({ allChecked: e.target.checked }, () => {
              // setState的第二个参数，获取异步更新之后的值
              // console.log('allChecked:', allChecked)
              console.log(this.state.allChecked, '-------------')
              this.state.list.forEach((item) => {
                item.isSelected = this.state.allChecked
              })
              this.setState({})
              console.log('this.state.list: ', this.state.list)
            })
          }}
        />

        {this.state.showToast ? (
          <Toast
            handleCloseToast={(index) => {
              this.setState({
                showToast: false,
              })
            }}
          ></Toast>
        ) : null}

        <header className={cartStyle['cart-header']}>
          <HeaderBar />
        </header>
        <main className={cartStyle['cart-main']}>
          {list.map((item, i) => {
            return (
              <CartList
                key={item.id}
                item={item}
                handleSelected={({ id, checked }) => this.handleSelected({ id, checked })}
                handleAddItem={(id) => this.handleAddItem(id)}
                handleReduceItem={(id) => this.handleReduceItem(id)}
              />
            )
          })}
        </main>
        <div className={cartStyle['cart-footer']}>
          <FooterBar></FooterBar>
        </div>
      </div>
    )
  }
}
